﻿<template>
  <a-card :bordered="false">
    <div class="table-operator">
      <a-button v-if="hasPerm('CustomerGroup.Add')" type="primary" icon="plus" @click="handleAdd()">新建分组</a-button>
      <a-button
        v-if="hasPerm('CustomerGroup.Delete')"
        type="primary"
        icon="minus"
        @click="handleDelete(selectedRowKeys)"
        :disabled="!hasSelected()"
        :loading="loading"
      >删除
      </a-button>
      <a-button type="primary" icon="redo" @click="getDataList()">刷新</a-button>
    </div>

    <!-- <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="查询类别">
              <a-select allowClear v-model="queryParam.condition">
                <a-select-option key="GroupName">分组名称</a-select-option>
                <a-select-option key="Remark">备注</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.keyword" placeholder="关键字" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
              >查询</a-button
            >
            <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div> -->

    <a-table
      ref="table"
      :scroll="{ y: 570 }"
      :columns="columns"
      :rowKey="(row, index) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small"
    >
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a v-if="hasPerm('CustomerGroup.Edit')" @click="handleEdit(record.Id)">编辑</a>
          <a-divider v-if="hasPerm('CustomerGroup.Edit') && hasPerm('CustomerGroup.Delete')" type="vertical"/>
          <a v-if="hasPerm('CustomerGroup.Delete')" @click="handleDelete([record.Id])">删除</a>
          <a-divider v-if="hasPerm('CustomerGroup.Delete') && hasPerm('CustomerGroup.Delete')" type="vertical"/>
          <!--<a @click="Group(record)">客户分组</a>-->
          <!--<a-divider type="vertical" />-->
          <a @click="GroupTable(record)">客户分组</a>
          <a-divider type="vertical"/>
          <a @click="GroupAllocation(record)">组分配</a>
          <a-divider type="vertical"/>
          <a @click="ResponsiblePerson(record)">主负责人</a>
        </template>
      </span>
    </a-table>
    <a-modal
      :maskClosable="false"
      :title="modalTitle"
      :visible="modalVisible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-select
        allowClear
        v-model="selectedUser"
        :mode="modalTitle === '请选择主负责人' ? '' : 'multiple'"
        :filter-option="filterOption"
        style="width: 100%"
        :placeholder="modalTitle"
      >
        <a-select-option
          v-for="item in modalTitle === '请选择主负责人' ? AllocationUserList : userList"
          :key="modalTitle === '请选择主负责人' ? item.UserId : item.Id"
        >
          {{ modalTitle === '请选择主负责人' ? item.UserName : item.RealName }}
        </a-select-option>
      </a-select>
    </a-modal>
    <edit-form ref="editForm" :parentObj="this"></edit-form>
    <Group ref="group" :parentObj="this"></Group>
    <group-table ref="grouptable" :parentObj="this"></group-table>
  </a-card>
</template>

<script>
import EditForm from './EditForm'
import Group from './Group.vue'
import moment from 'moment'
import GroupTable from '@/views/CustomerManagement/CustomerGroup/GroupTable'

const columns = [
  { title: '分组名称', dataIndex: 'GroupName', width: '10%' },
  {
    title: '创建时间',
    dataIndex: 'CreateTime',
    align: 'center',
    width: '8%',
    scopedSlots: { customRender: 'CreateTime' }
  },
  { title: '客户数量', dataIndex: 'CustCount', align: 'center', width: '5%' },
  { title: '主负责人', dataIndex: 'PrincipalName', align: 'center', width: '8%' },
  {
    title: '本组分配给',
    dataIndex: 'AllocationUserList',
    customRender: (value, row) => {
      if (row.AllocationUserList.length > 0) {
        return row.AllocationUserList.map(item => item.UserName).join('/')
      } else {
        return '未分配负责人'
      }
    },
    align: 'left',
    width: '32%'
  },
  { title: '备注', dataIndex: 'Remark' },
  { title: '操作', dataIndex: 'action', align: 'left', width: '20%', scopedSlots: { customRender: 'action' } }
]

export default {
  components: {
    GroupTable,
    EditForm,
    Group
  },
  mounted () {
    this.getDataList()
    this.getUserList()
  },
  data () {
    return {
      modalTitle: '请选择分配给',
      modalVisible: false,
      confirmLoading: false,
      data: [],
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      tol: 0,
      filters: {},
      sorter: { field: 'CreateTime', order: 'desc' },
      loading: false,
      columns,
      queryParam: [],
      selectedRowKeys: [],
      userList: [],
      selectedUser: '',
      entity: {},
      AllocationUserList: []
    }
  },
  methods: {
    handleOk () {
      this.confirmLoading = true
      if (this.modalTitle === '请选择主负责人') {
        this.$http
          .post('/CustomerManagement/CustomerGroup/UpdateDataByCondition', {
            Conditions: [
              {
                Condition: 'PrincipalId',
                Keyword: this.selectedUser ? this.selectedUser : 'null'
              }
            ],
            ids: [this.entity.Id]
          })
          .then(res => {
            if (res.Success) {
              this.getDataList()
              this.$message.success('操作成功')
              this.modalVisible = false
            } else {
              this.$message.error(res.Msg)
            }
            this.confirmLoading = false
          })
      } else {
        // if (this.selectedUser.length <= 0) return this.$message.error('请选择分配给')
        this.$http
          .post('/CustomerManagement/Cust_GroupAllocationOfUser/SaveDataOfMoreUser', {
            GroupId: this.entity.Id,
            GroupName: this.entity.Name,
            SalesmanIds: this.selectedUser
          })
          .then(res => {
            if (res.Success) {
              this.getDataList()
              this.$message.success('操作成功')
              this.modalVisible = false
            } else {
              this.$message.error(res.Msg)
            }
            this.confirmLoading = false
          })
      }
    },
    handleCancel () {
      this.modalVisible = false
    },
    getUserList () {
      this.$http
        .post('/Base_Manage/Base_User/GetDataList', {
          PageIndex: 1,
          PageRows: 999,
          SortField: 'CreateTime',
          SortType: 'desc',
          Search: {}
        })
        .then(resJson => {
          this.loading = false
          this.userList = resJson.Data
        })
    },
    GroupAllocation (record) {
      this.modalVisible = true
      this.modalTitle = '请选择分配给'
      this.selectedUser = record.AllocationUserList.map(item => item.UserId)
      this.entity.Id = record.Id
      this.entity.Name = record.GroupName
    },
    ResponsiblePerson (record) {
      this.modalVisible = true
      this.modalTitle = '请选择主负责人'
      this.selectedUser = record.PrincipalId === 'null' ? '' : record.PrincipalId
      this.entity.Id = record.Id
      this.AllocationUserList = record.AllocationUserList
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.getDataList()
    },
    getDataList () {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/CustomerManagement/CustomerGroup/GetDataListByMoreCondition', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data

          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    Group (row) {
      this.$refs.group.openForm(row)
    },
    GroupTable (row) {
      this.$refs.grouptable.openForm(row)
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    handleAdd () {
      this.$refs.editForm.openForm(null, '新建客户分组表信息')
    },
    handleEdit (id) {
      this.$refs.editForm.openForm(id, '编辑客户分组表信息')
    },
    handleDelete (ids) {
      var thisObj = this
      this.$confirm({
        title: '删除此客户分组将移除分组下所有客户以及分组状态,确认删除吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            thisObj.$http.post('/CustomerManagement/CustomerGroup/DeleteData', ids).then(resJson => {
              resolve()

              if (resJson.Success) {
                thisObj.$message.success('操作成功!')

                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
          })
        }
      })
    },
    timeFormat (val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD')
    },

    filterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  }
}
</script>
